/*
 * Copyright 2011 Manuel Bueno
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package cronome;

import java.util.Date;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 * @author Manuel Bueno
 */
// mrbueno@gmail.com
public class CronoMe extends MIDlet implements CommandListener {
    
    private boolean midletPaused = false;

//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
private List marksList;
private Command exitCommand;
private Command okCommand;
//</editor-fold>//GEN-END:|fields|0|
    private boolean running = false;
    private long mark1;
    /**
     * The CronoMe constructor.
     */
    public CronoMe() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
/**
 * Initializes the application.
 * It is called only once when the MIDlet is started. The method is called before the <code>startMIDlet</code> method.
 */
private void initialize () {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
}//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Started point.
 */
public void startMIDlet () {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        running = false;
switchDisplayable (null, getMarksList ());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
}//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
/**
 * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
 */
public void resumeMIDlet () {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
}//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
/**
 * Switches a current displayable in a display. The <code>display</code> instance is taken from <code>getDisplay</code> method. This method is used by all actions in the design for switching displayable.
 * @param alert the Alert which is temporarily set to the display; if <code>null</code>, then <code>nextDisplayable</code> is set immediately
 * @param nextDisplayable the Displayable to be set
 */
public void switchDisplayable (Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
Display display = getDisplay ();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
if (alert == null) {
display.setCurrent (nextDisplayable);
} else {
display.setCurrent (alert, nextDisplayable);
}//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
}//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|



//<editor-fold defaultstate="collapsed" desc=" Generated Method: addMark ">//GEN-BEGIN:|28-entry|0|29-preAction
/**
 * Performs an action assigned to the addMark entry-point.
 */
public void addMark () {//GEN-END:|28-entry|0|29-preAction
        
        long mark2 = System.currentTimeMillis();
        long dif = mark2-mark1;
        
        getMarksList().append(millisToFormatedTime(dif), null);
        mark1 = mark2;
        // write pre-action user code here

switchDisplayable (null, getMarksList ());//GEN-LINE:|28-entry|1|29-postAction
        // write post-action user code here
}//GEN-BEGIN:|28-entry|2|
//</editor-fold>//GEN-END:|28-entry|2|



//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
/**
 * Called by a system to indicated that a command has been invoked on a particular displayable.
 * @param command the Command that was invoked
 * @param displayable the Displayable where the command was invoked
 */
public void commandAction (Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
if (displayable == marksList) {//GEN-BEGIN:|7-commandAction|1|16-preAction
if (command == List.SELECT_COMMAND) {//GEN-END:|7-commandAction|1|16-preAction
                // write pre-action user code here
marksListAction ();//GEN-LINE:|7-commandAction|2|16-postAction
                // write post-action user code here
} else if (command == exitCommand) {//GEN-LINE:|7-commandAction|3|20-preAction
                // write pre-action user code here
exitMIDlet ();//GEN-LINE:|7-commandAction|4|20-postAction
                // write post-action user code here
} else if (command == okCommand) {//GEN-LINE:|7-commandAction|5|23-preAction
                // write pre-action user code here
isRunning ();//GEN-LINE:|7-commandAction|6|23-postAction
                // write post-action user code here
}//GEN-BEGIN:|7-commandAction|7|7-postCommandAction
}//GEN-END:|7-commandAction|7|7-postCommandAction
        // write post-action user code here
}//GEN-BEGIN:|7-commandAction|8|
//</editor-fold>//GEN-END:|7-commandAction|8|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: marksList ">//GEN-BEGIN:|14-getter|0|14-preInit
/**
 * Returns an initiliazed instance of marksList component.
 * @return the initialized component instance
 */
public List getMarksList () {
if (marksList == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
marksList = new List ("Marks", Choice.IMPLICIT);//GEN-BEGIN:|14-getter|1|14-postInit
marksList.addCommand (getExitCommand ());
marksList.addCommand (getOkCommand ());
marksList.setCommandListener (this);
marksList.setFitPolicy (Choice.TEXT_WRAP_DEFAULT);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
}//GEN-BEGIN:|14-getter|2|
return marksList;
}
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: marksListAction ">//GEN-BEGIN:|14-action|0|14-preAction
/**
 * Performs an action assigned to the selected list element in the marksList component.
 */
public void marksListAction () {//GEN-END:|14-action|0|14-preAction
        // enter pre-action user code here
String __selectedString = getMarksList ().getString (getMarksList ().getSelectedIndex ());//GEN-LINE:|14-action|1|14-postAction
        // enter post-action user code here
}//GEN-BEGIN:|14-action|2|
//</editor-fold>//GEN-END:|14-action|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: exitCommand ">//GEN-BEGIN:|19-getter|0|19-preInit
/**
 * Returns an initiliazed instance of exitCommand component.
 * @return the initialized component instance
 */
public Command getExitCommand () {
if (exitCommand == null) {//GEN-END:|19-getter|0|19-preInit
            // write pre-init user code here
exitCommand = new Command ("Exit", Command.EXIT, 0);//GEN-LINE:|19-getter|1|19-postInit
            // write post-init user code here
}//GEN-BEGIN:|19-getter|2|
return exitCommand;
}
//</editor-fold>//GEN-END:|19-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">//GEN-BEGIN:|22-getter|0|22-preInit
/**
 * Returns an initiliazed instance of okCommand component.
 * @return the initialized component instance
 */
public Command getOkCommand () {
if (okCommand == null) {//GEN-END:|22-getter|0|22-preInit
            // write pre-init user code here
okCommand = new Command ("Ok", Command.OK, 0);//GEN-LINE:|22-getter|1|22-postInit
            // write post-init user code here
}//GEN-BEGIN:|22-getter|2|
return okCommand;
}
//</editor-fold>//GEN-END:|22-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: isRunning ">//GEN-BEGIN:|38-if|0|38-preIf
/**
 * Performs an action assigned to the isRunning if-point.
 */
public void isRunning () {//GEN-END:|38-if|0|38-preIf
        // enter pre-if user code here
if (running) {//GEN-LINE:|38-if|1|39-preAction
            // write pre-action user code here
addMark ();//GEN-LINE:|38-if|2|39-postAction
            // write post-action user code here
} else {//GEN-LINE:|38-if|3|40-preAction
            // write pre-action user code here
            running = true;
initTimer ();//GEN-LINE:|38-if|4|40-postAction
            // write post-action user code here
}//GEN-LINE:|38-if|5|38-postIf
        // enter post-if user code here
}//GEN-BEGIN:|38-if|6|
//</editor-fold>//GEN-END:|38-if|6|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: initTimer ">//GEN-BEGIN:|42-entry|0|43-preAction
/**
 * Performs an action assigned to the initTimer entry-point.
 */
public void initTimer () {//GEN-END:|42-entry|0|43-preAction
        // write pre-action user code here
        getMarksList().append("00:00:00.0", null);
        mark1 = System.currentTimeMillis();
        
switchDisplayable (null, getMarksList ());//GEN-LINE:|42-entry|1|43-postAction
        // write post-action user code here
}//GEN-BEGIN:|42-entry|2|
//</editor-fold>//GEN-END:|42-entry|2|

    /**
     * Returns a display instance.
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started.
     * Checks whether the MIDlet have been already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     * @param unconditional if true, then the MIDlet has to be unconditionally terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }
    
    private String millisToFormatedTime(long now) {
        String hour = null;
        if (now >= 3600000) {
            hour = now / 3600000 + "";
            if (hour.length() < 2) {
                hour = "0" + hour;
            }
            now = now % 36000;
        }
        String min = null;
        if (now >= 60000) {
            min = now / 60000 + "";
            if (min.length() < 2) {
                min = "0" + min;
            }
            now = now % 60000;
        }
        String sec = now / 1000 + "";
        if(sec.length() < 2) sec = "0"+sec;
        now = now % 1000;
        if (hour == null) {
            hour = "00";
        }
        if (min == null) {
            min = "00";
        }
        return hour+":"+min+":"+sec+"."+now;
    }
}
